//
//  HResponse.m
//  Request
//
//  Created by 侯伟 on 2019/4/19.
//  Copyright © 2019年 侯伟. All rights reserved.
//

#import "HResponse.h"
#import "YYModel.h"
#import "Toast.h"
#import "RSA.h"
#import "Sign.h"
#import "AppConfig.h"

#define SuccessCode     10000

#define TokenExpiredCode    10402

@implementation HResponse

- (NSString*)jsonString{
    return [self.jsondata yy_modelToJSONString];
}

- (BOOL)isOK{
    return 200 == self.code;
}

- (APIError*)error{
    
    if(self.isOK) return NULL;
    
    if(self.code > 200 && self.code < 400){
        return [APIError errorWith:self.code msg:self.msg.length?self.msg:@"网络请求错误"];
    }else{
        return [APIError errorWith:self.code msg:self.msg.length?self.msg:@"未知错误"];
    }
}

- (HResponse*)success:(void (^)(id _Nonnull))success{
    
    if(!self.isOK)
        return self;
    if(success){
        success(self.data);
    }
    return self;
}

- (HResponse*)failure:(void (^)(APIError * _Nonnull))failure{
    
    if(self.isOK){
        return self;
    }
    if(failure){
        failure(self.error);
    }
    return self;
    
}

- (HResponse*)failureDefalut{
    
    return [self failure:^(APIError * _Nonnull error) {
        if(error.errorMsg.length){
            [Toast toast:error.errorMsg];
        }else{
            [Toast toast:@"请求失败,请稍后重试"];
        }
    }];
}

@end

